package com.qili.core.quartz.CustomQuartz;

import cn.hutool.core.util.IdUtil;
import com.qili.core.utils.DictTypes;
import com.qili.entity.base.BaseDict;
import com.qili.entity.supervisor.ProjectNotice;
import com.qili.entity.supplier.SupplierProject;
import com.qili.entity.supplier.SupplierProjectAccept;
import com.qili.entity.supplier.SupplierProjectPubNotice;
import com.qili.entity.supplier.dto.SupplierProjectAcceptDTO;
import com.qili.entity.sys.SysUser;
import com.qili.entity.sys.SysUserWorkExperience;
import com.qili.service.SysUserService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.supervisor.ProjectNoticeServie;
import com.qili.service.supplier.SupplierProjectAcceptService;
import com.qili.service.supplier.SupplierProjectManagerService;
import com.qili.service.supplier.SupplierProjectPubNoticeService;
import com.qili.service.sys.SysUserWorkExperienceService;
import com.qili.util.DateUtil;
import com.qili.util.JsonUtil;
import com.qili.util.StringUtil;
import lombok.extern.java.Log;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaoyongke
 * @date 2021/4/7
 * @description 内部、外部发布的项目--若Y日内未确认，则默认同意推荐结果
 * 系统推荐出项目中标人后推送消息给发布人：您发布的XXX项目系统推荐中标人为XXX，请在Y日内进行确认？
 * 若确认，则中标人确定，若Y日内未确认，则默认同意推荐结果，若不同意推荐结果，则由发布人自行选择。
 */

@Log
public class TjNoConfirmJob implements Job {
    @Autowired
    SysUserService sys;
    @Autowired
    private SupplierProjectPubNoticeService supplierProjectPubNoticeService;
    @Autowired
    private SupplierProjectManagerService supplierProjectManagerService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    ProjectNoticeServie projectNoticeServie;
    @Autowired
    SupplierProjectAcceptService supplierProjectAcceptService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    BaseCompanyService baseCompanyService;

    @Autowired
    SysUserWorkExperienceService userWorkExperienceService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("TjNoConfirmJob：启动任务=======================");
        run();
        System.out.println("TjNoConfirmJob：下次执行时间=====" +
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                        .format(context.getNextFireTime()) + "==============");
    }

    public void run() {

        log.info("TjNoConfirmJob=======开始==================================");
        String lockkey = "TjNoConfirmJob_key";
        String uuId = IdUtil.simpleUUID();
        try {
            lock(lockkey, uuId);
            //(2)到招标截止时间，有一人应接：则推荐此人为中标人。
            saveNoConfirm();

        } catch (Exception e) {
            log.info("TjNoConfirmJob=======出现异常了==================================");
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            log.info("TjNoConfirmJob=======释放锁==================================");
            unlock(lockkey, uuId);
        }
    }

    /**
     * @param
     * @Author:zhaoyongke
     * @Description: 到招标截止时间，有一人应接：则推荐此人为中标人。
     * @Date:16:09 2021/4/12
     */
    public void saveNoConfirm() {
        try {
            // 外部发布的单位 您发布的XXX项目系统推荐中标人为XXX，请在Y日内进行确
            String wyvalue = "";
            List<BaseDict> typeListSsbl = baseDictService.selectByTypeCode(DictTypes.WXQR001.getType());
            if (typeListSsbl.size() > 0) {
                BaseDict bzjbl = typeListSsbl.get(0);
                wyvalue = bzjbl.getBadtLevel1();
            }

            String nyvalue = "";
            List<BaseDict> typeListSsblN = baseDictService.selectByTypeCode(DictTypes.NXQR001.getType());
            if (typeListSsbl.size() > 0) {
                BaseDict bzjbl = typeListSsblN.get(0);
                nyvalue = bzjbl.getBadtLevel1();
            }

            Example e = new Example(SupplierProject.class);
            Example.Criteria c = e.createCriteria();
            c.andEqualTo("status", "006");
            // 推荐过的项目
            c.andEqualTo("tjStatus", "1");
            // 没有确认
            c.andEqualTo("isConfirm", "0");
            List<SupplierProject> supplierProjects = supplierProjectManagerService.selectByExample(e);
            for (int i = 0; i < supplierProjects.size(); i++) {
                SupplierProject project = supplierProjects.get(i);
                String tjPerson = project.getTjPerson();
                String tjDatestr = project.getTjDate();
                Date tjDate = DateUtil.parseDate(tjDatestr, "yyyy-MM-dd HH:mm");
                String publishType = project.getPublishType();
                int i2 = 0;
                if ("001".equals(publishType)) {
                    Double x = Double.valueOf(nyvalue) * 24;
                    i2 = x.intValue();
                } else if ("002".equals(publishType)) {
                    Double x = Double.valueOf(wyvalue) * 24;
                    i2 = x.intValue();
                }
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(tjDate);
                calendar.add(Calendar.HOUR, i2);
                /*获得推荐日期y天后的日期*/
                Date datebeforex = new Date(calendar.getTimeInMillis());
                Date currdate = new Date();
                if (currdate.after(datebeforex)) {
                    updateZb(project.getSupProjectId(), tjPerson, "002");
                    sendNoticeToXfZb(project.getSupProjectId(), tjPerson, project.getPublishType() + "没有确认，系统默认推荐中标人");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }


    }


    /**
     * @param projectId
     * @param acceptId
     * @Author:zhaoyongke
     * @Description:
     * @Date:16:45 2021/4/13
     */
    public void updateZb(String projectId, String acceptId, String type) throws Exception {
        String accpt1 = "";
        String time = DateUtil.getCurrentDateTimeString();
        //查询中标公司和未中标公司  更新状态
        SupplierProjectAccept notdto = new SupplierProjectAccept();
        notdto.setSupProjectId(projectId);
        List<SupplierProjectAccept> list = supplierProjectAcceptService.select(notdto);
        if (list != null && list.size() > 0) {
            for (SupplierProjectAccept a : list) {
                if ("001".equals(type)) {
                    if (!acceptId.equals(a.getSupAcceptId())) {
                        a.setIsZb("0");
                        supplierProjectAcceptService.updateByPrimaryKeySelective(a);
                    } else {
                        // 生成账号
                        saveCreateZh(a, projectId);
                        a.setZbDate(time);
                        a.setIsZb("1");
                        supplierProjectAcceptService.updateByPrimaryKeySelective(a);
                    }
                } else {
                    if (!acceptId.equals(a.getAcceptBy())) {
                        // 推荐的招标人
                        a.setIsZb("0");
                        supplierProjectAcceptService.updateByPrimaryKeySelective(a);
                    } else {
                        accpt1 = a.getSupAcceptId();
                        // 生成账号
                        saveCreateZh(a, projectId);
                        a.setZbDate(time);
                        a.setIsZb("1");
                        supplierProjectAcceptService.updateByPrimaryKeySelective(a);
                    }

                }

            }
        }
        //更新中标项目
        String accId = acceptId;
        if ("001".equals(type)) {
            accId = acceptId;
        } else {
            accId = accpt1;
        }
        SupplierProjectAccept adto = supplierProjectAcceptService.selectByPrimaryKey(accId);
        SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(projectId);
        project.setZbStatus("1");
        project.setZbCompany(adto.getCompanyId());
        project.setZbDate(time);
        project.setZbComType(adto.getComType());
        project.setZbBy(adto.getAcceptBy());
        project.setSupProjectId(projectId);
        project.setStatus("004");
        supplierProjectManagerService.updateByPrimaryKey(project);
        saveGs(project);


    }

    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description: 中标以后自动公示
     * @Date:10:23 2021/9/8
     */
    public void saveGs(SupplierProject dto) {

        SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(dto.getSupProjectId());
        SupplierProjectPubNotice pubNotice = new SupplierProjectPubNotice();
        pubNotice.setSupProjectId(dto.getSupProjectId());
        pubNotice.setPubComType(project.getPubComType());
        pubNotice.setPubCompany(project.getPublishCompany());
        pubNotice.setStartDate(DateUtil.getCurrentDateString());
        String gsDays = dto.getGsDays();
        if (StringUtil.isNotBlank(gsDays)) {
            Double aDouble = Double.valueOf(gsDays) * 24;
            int addHours = aDouble.intValue();
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(new Date());
            calendar.add(Calendar.HOUR, addHours);
            Date dateend = new Date(calendar.getTimeInMillis());
            pubNotice.setEndDate(DateUtil.formatDate(dateend, "yyyy-MM-dd HH:mm"));
        }
        /**
         * 公示状态 0  未公示 1 公示中  2 结束
         */
        pubNotice.setGsStatus("1");
        // 中标人
        pubNotice.setZbBy(project.getZbBy());
        pubNotice.setSupProjectId(project.getSupProjectId());
        pubNotice.setZbComType(project.getZbComType());
        pubNotice.setZbCompany(project.getZbCompany());
        supplierProjectPubNoticeService.insertSelective(pubNotice);
        project.setIsGs("1");
        supplierProjectManagerService.updateByPrimaryKey(project);

    }


    public void saveCreateZh(SupplierProjectAccept accept, String projectId) throws Exception {
        //  项目应接人----【供方合同负责人】角色权限
        String acceptBy = accept.getAcceptBy();
        SysUser sysUseraccept = sysUserService.selectByPrimaryKey(acceptBy);
        String personType = sysUseraccept.getPersonType();
        String source = sysUseraccept.getSource();
        //添加默认角色【供方合同负责人】角色权限
        List<String> initRoleList = new ArrayList<String>();
        initRoleList.add("gfhtperson");
        sysUserService.setMenuAndRolesWhenRegist(sysUseraccept, initRoleList);
        //输入的项目经理生成账号 和 权限
        SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(projectId);
        String projectType = project.getProjectType();
        if (projectType.indexOf("001") > -1) {
            //监理
            String jlManagerPerson = accept.getJlManagerPerson();
            if (StringUtil.isBlank(jlManagerPerson)) {
                String jlManagerPersonName = accept.getJlManagerPersonName();
                SysUser sysUser = saveCreateUser(jlManagerPersonName, sysUseraccept, "001", "xmjl");
                accept.setJlManagerPerson(sysUser.getId());
            }

        }
        if (projectType.indexOf("002") > -1) {
            //咨询
            String zxManagerPerson = accept.getZxManagerPerson();
            if (StringUtil.isBlank(zxManagerPerson)) {
                String zxManagerPersonName = accept.getZxManagerPersonName();
                SysUser sysUser = saveCreateUser(zxManagerPersonName, sysUseraccept, "002", "zxxmjl");
                accept.setZxManagerPerson(sysUser.getId());
            }

        }
        if (projectType.indexOf("003") > -1) {
            //检测
            String jcManagerPerson = accept.getJcManagerPerson();
            if (StringUtil.isBlank(jcManagerPerson)) {
                String jcManagerPersonName = accept.getJcManagerPersonName();
                SysUser sysUser = saveCreateUser(jcManagerPersonName, sysUseraccept, "003", "jcxmjl");
                accept.setJcManagerPerson(sysUser.getId());
            }

        }
        if (projectType.indexOf("100") > -1) {
            //其他
            String qtManagerPerson = accept.getQtMagagerPerson();
            if (StringUtil.isBlank(qtManagerPerson)) {
                String qtManagerPersonName = accept.getQtManagerPersonName();
                SysUser sysUser = saveCreateUser(qtManagerPersonName, sysUseraccept, "100", "qtxmjl");
                accept.setQtMagagerPerson(sysUser.getId());
            }

        }


    }

    /**
     * @param realName
     * @param sysUseraccept
     * @param ywType
     * @param roleName
     * @Author:zhaoyongke
     * @Description: 创建账号
     * @Date:11:30 2021/4/9
     */
    public SysUser saveCreateUser(String realName, SysUser sysUseraccept, String ywType, String roleName) throws Exception {
        SysUser user = new SysUser();
        user.setUsername(realName);
        if ("001".equals(sysUseraccept.getPersonType())) {
            // 个人
        } else {
            // 组织
            user.setCompanyName(sysUseraccept.getCompanyName());
        }
        user.setSource("002");
        // 供需类型
        user.setGxType("001");
        // 人員类型
        user.setPersonType(sysUseraccept.getPersonType());
        user.setYwType(ywType);
        saveNewUserIdForProjectLeaderAndUnits(user);
        // 赋予角色
        List<String> userRoleNameList = new ArrayList<String>();
        userRoleNameList.add(roleName);
        sysUserService.setMenuAndRolesWhenRegist(user, userRoleNameList);
        return user;
    }

    /**
     * 注册新用户,
     * 查找系统中是否存在同名用户
     * 如果存在同名用户,
     * 如果同一个公司中存在同名用户,给user设置id为该同名用户id
     * 如果同名用户不为同一个公司,那么根据规则生成新用户,给user设置新生成的用户id
     *
     * @param user
     * @return
     */
    public void saveNewUserIdForProjectLeaderAndUnits(SysUser user) throws Exception {
        SysUser sameNameUser = new SysUser();
        sameNameUser.setRealName(user.getUsername());
        //查询同名的用户
        List<SysUser> listuser = sysUserService.select(sameNameUser);
        Integer count = 0;
        if (listuser.size() > 0) {
            //存在相同username的账号
       /*     SysUser realNameUser = new SysUser();
            realNameUser.setRealName(user.getUsername());
            List<SysUser> listuserReal = sysUserService.select(realNameUser);*/
            for (int i = 0; i < listuser.size(); i++) {
                //相同公司 相同姓名
                SysUser dbUser = listuser.get(i);
                String dbCompanyName = dbUser.getCompanyName() + "";
                String dbRealName = dbUser.getRealName() + "";
                if (dbRealName.equals(user.getUsername()) && (user.getCompanyName() + "").equals(dbCompanyName)) {
                    // 相同姓名 相同公司
                    user.setId(dbUser.getId());
                    return;
                } else if (dbRealName.equals(user.getUsername()) && !user.getCompanyName().equals(dbCompanyName)) {
                    // 相同姓名不同公司
                    count++;
                } else {
                    //不同姓名 公司相同、不同姓名不同公司
                    count++;
                }
            }
        }
        //生成账号
        SysUser newUser = new SysUser();
        //获取用户名
        String username = getUserName(user, count);
        newUser.setUsername(username);
        newUser.setCompanyName(user.getCompanyName());
        newUser.setPassword("12345678");
        newUser.setRealName(user.getUsername());
        newUser.setGxType(user.getGxType());
        newUser.setYwType(user.getYwType());
        newUser.setPersonType(user.getPersonType());
        newUser.setSource(user.getSource());
        newUser.setCreateDate(DateUtil.getCurrentDateTime());
        sysUserService.setUserFilePath(newUser);
        sysUserService.insertSelective(newUser);

        SysUserWorkExperience nowWork = user.getNowWork();
        if (nowWork != null) {
            sysUserService.setUserFilePath(newUser);
            nowWork.setIfNow("1");
            nowWork.setSuId(newUser.getId());
            userWorkExperienceService.insertSelective(nowWork);
        }

        user.setId(newUser.getId());
        user.setUsername(newUser.getUsername());
        user.setRealName(newUser.getRealName());

    }

    /**
     * @param user
     * @param count
     * @Author:zhaoyongke
     * @Description: 获取用户名
     * @Date:17:51 2020/12/31
     */
    public String getUserName(SysUser user, int count) {
        String userName = setUserName(user, count);
        int countUser = sysUserService.checkUser(userName);
        if (countUser != 0) {
            count = count + 1;
            userName = setUserName(user, count);
            int countUser1 = sysUserService.checkUser(userName);
            if (countUser1 > 0) {
                userName = getUserName(user, count);
            }
        }
        return userName;
    }

    /**
     * @param user
     * @param count
     * @Author:zhaoyongke
     * @Description:设置用户名
     * @Date:17:51 2020/12/31
     */
    public String setUserName(SysUser user, int count) {
        SysUser newUser = new SysUser();
        if (count > 0) {
            newUser.setUsername(user.getUsername() + "0" + count);
        } else {
            newUser.setUsername(user.getUsername());
        }
        return newUser.getUsername();
    }

    /**
     * @Author:zhaoyongke
     * @Description: 发送需方--中标消息
     * @Date:14:30 2021/4/7
     */
    public void sendNoticeToXfZb(String projectId, String zbperson, String remark) throws Exception {
        SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(projectId);
        SysUser sysUser = sysUserService.selectByPrimaryKey(zbperson);
        String personType = sysUser.getPersonType();
        String realName = "";
        if ("001".equals(personType)) {
            // 个人
            realName = sysUser.getRealName();
        } else {
            realName = sysUser.getLinkPerson();
        }
        ProjectNotice notice = new ProjectNotice();
        notice.setLinkId(project.getSupProjectId());
        notice.setIsView("0");
        notice.setSendTo(project.getCreateBy());
        notice.setTitle("您发布的" + project.getProjectName() + "项目中标人为" + realName);
        notice.setNoticeType("108");// 中标人确认消息发送
        notice.setApplicantType("002");// 供需
        notice.setContent(project.getProjectName());
        notice.setCreateDate(DateUtil.getCurrentDateString());
        notice.setRemark(remark);
        projectNoticeServie.insertSelective(notice);
    }

    public void lock(String key, String uuId) {
        for (; ; ) {
            boolean r = stringRedisTemplate.opsForValue().setIfAbsent(key, uuId);
            stringRedisTemplate.expire(key, 600, TimeUnit.SECONDS);

            if (r) {
                return;
            } else {
                throw new RuntimeException("已经存在的执行程序...");
            }
        }
    }

    public void unlock(String key, String uuId) {
        if (uuId.equals(stringRedisTemplate.opsForValue().get(key))) {
            stringRedisTemplate.delete(key);
        }
    }



}
